package 工厂模式;


import 工厂模式.sender.EmailSender;
import 工厂模式.sender.ExpressSender;
import 工厂模式.sender.SMSSender;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;



public class SenderFactory {
	public static void main(String[] args) throws Exception {
		String path = System.getProperty("java.class.path");
		System.out.println(path);
		produceAll("EmailSender");
		produceAll("ExpressSender");
		produceAll("SMSSender");
		//SenderFactory senderFactory = new SenderFactory();
		//Sender produce = senderFactory.produce(SenderType.EMAIL);
		// 静态化 减少了反复调用
		Sender produce = SenderFactory.produce(SenderType.EMAIL);
	}


	/**
	 * 工厂一般都会静态化，避免重复调用带来的重复初始化。
	 * @param senderType
	 * @return
	 * @throws Exception
	 */
	static Sender produce(SenderType senderType) throws Exception {
		Sender sender = null;
		switch (senderType) {
			case SMS:
				sender = new SMSSender();
				break;
			case EMAIL:
				sender = new EmailSender();
				break;
			case EXPRESS:
				sender = new ExpressSender();
				break;
			default:
				sender = null;
				break;
		}
		return sender;
	}

	static Sender produceAll(String className) {
		Class<?> tClass = null;
		try {
			tClass = Class.forName("工厂模式.sender." +className);
			Sender s = (Sender)tClass.getDeclaredConstructor().newInstance();
			s.send("");
		} catch (ClassNotFoundException | NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return null;
	}
}
